package com.mssh.login.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;
import java.util.regex.Pattern;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2022/09/12/11:16
 * @Description: 公共的工具类
 */
public class CommonUtil {

    private static final Logger logger = LogManager.getLogger(CommonUtil.class);

    /**
     * 手机号效验
     * @param phone
     * @return
     */
    public static boolean verifyPhone(String phone) {
        String regex = "^[1]([3-9])[0-9]{9}$";
        boolean isMatch = false;
        if (StringUtils.isEmpty(phone)) { ;
            logger.warn("手机号不能为空");
        } else if (phone.length() != 11) {
            logger.warn("手机号应为11位数");
        } else {
            isMatch = Pattern.matches(regex, phone);
            String msg = isMatch?"当前字符是为手机号，验证通过！":"当前字符不为手机号，验证未通过！";
            logger.warn(String.format("%s:%s:%s:%s", "手机号验证结果为：", isMatch, "，", msg));
        }
        return isMatch;
    }

    /**
     * 邮箱地址效验
     * @param phone
     * @return
     */
    public static boolean verifyEmail(String phone) {
        String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
        boolean isMatch = false;
        if (StringUtils.isEmpty(phone)) { ;
            logger.warn("邮箱地址不能为空");
        } else {
            isMatch = Pattern.matches(regex, phone);
            String msg = isMatch?"当前字符串是为邮箱地址，验证通过！":"当前字符串不为邮箱地址，验证未通过！";
            logger.warn(String.format("%s:%s:%s:%s", "邮箱地址验证结果为：", isMatch, "，", msg));
        }
        return isMatch;
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return true-空，false-不为空
     */
    public static boolean isEmpty(String str){
        if(str != null && !"".equals(str.trim())){
            return false;
        }
        return true;
    }

    /**
     * 根据生日获取年龄
     * @param birthday
     * @return
     */
    public static String getAgeByBirthday(String birthday) throws Exception {
        String age = "";
        SimpleDateFormat sdf =new SimpleDateFormat();
        if(isEmpty(birthday)){
            logger.info("根据生日获取年龄失败，传入生日参数为空！");
            throw new Exception("根据生日获取年龄失败，生日不能为空！");
        }
        LocalDate currentDate = LocalDate.now();
        LocalDate birthDate = LocalDate.parse(birthday);
        Period period = Period.between(birthDate, currentDate);
        int year = period.getYears();
        if(year < 0){
            logger.info("根据生日获取年龄失败，生日[{}]不能大于当前日期[{}]！", birthday, sdf.format(new Date()));
            throw new Exception("根据生日获取年龄失败，生日不能大于当前日期！");
        }else{
            age = String.valueOf(year);
        }
        return age;
    }

}
